#include <stdio.h>
#include <stdbool.h>

#define size 3

void InitBoard(char (*board)[size])
{
    for(int i = 0; i < size; i++)
    {
        for(int j = 0; j < size; j++)
        {
            board[i][j] = ' ';
        }
    }
}

void PrintBoard(char (*board)[size])
{
    for(int i = 0; i < size; i++)
    {
        for(int j = 0; j < size; j++)
        {
            printf("%c",board[i][j]);
            if(j < size-1)
            printf(" |");
        }
        printf("\n");
        if(i < size-1)
        printf("--|--|--\n");
    }
}

bool MakeMove(char (*board)[size],int row,int column,char player)
{
    if(row < 0 || row >= size || column < 0 || column >= size)
    {
        printf("非法位置，请重新选择位置");
        return false;
    }

    if(board[row][column] != ' ')
    {
        printf("该位置已经有棋子了，请重新选择位置\n");
        return false;
    }

    board[row][column] = player;
    return true;
}

bool CheckIsWin(char (*board)[size],char player)
{
    for(int i = 0; i < size; i++)
    {
        if(board[i][0] == player && board[i][1] == player && board[i][2] == player)
        return true;
        if(board[0][i] == player && board[1][i] == player && board[2][i] == player)
        return true;
    }
    if(board[0][0] == player && board[1][1] == player && board[2][2] == player)
    return true;
    if(board[2][0] == player && board[1][1] == player && board[0][2] == player)
    return true;
    return false;
}

bool CheckIsDraw(char (*board)[size])
{
    for(int i = 0; i < size; i++)
    {
        for(int j = 0; j < size; j++)
        {
            if(board[i][j] == ' ')
            return false;
        }
    }
    return true;
}

int main()
{
    char board[size][size] = {0};
    InitBoard(board);
    //PrintBoard(board);
    char player = 'X';
    while(1)
    {
        PrintBoard(board);
        int row = 0,column = 0;
        printf("请选手%c下棋:",player);
        scanf("%d %d",&row,&column);
        if(MakeMove(board,row,column,player) == false)
        {
            continue;
        }

        if(CheckIsWin(board,player) == true)
        {
            PrintBoard(board);
            printf("选手%c获得了胜利!\n",player);
            break;
        }

        if(CheckIsDraw(board) == true)
        {
            printf("平局！游戏结束！\n");
            break;
        }

        player = (player == 'X') ? 'O' : 'X';
    }
    return 0;
}